<?php
namespace Modules\Cli\Tasks;

use Common\Models\UserWalletModel;
use Common\Models\UserAchievementModel;
use Common\Models\UserAchievementLogModel;
use Common\Models\UserWalletGoodsLogModel;

/**
 * 发放奖金
 */

class GrantTask extends TaskBase {
  private $currentTime;

  private $logger;

  public function initialize() {
    $this -> currentTime = time();

    $this -> logger = new \Phalcon\Logger\Adapter\File(BASE_PATH . 'runtime/logger/cli_'.date('Ymd').'_grant.log');
  }

  public function mainAction() {
    set_time_limit(0);
    ini_set('date.timezone', 'Asia/Shanghai');
    echo 'Granting...';

    $this -> logger -> begin();
    $this -> logger -> notice('————————————————' . $this -> currentTime . '————————————————'); 
    $this -> logger -> notice('***** $this -> getAchievement() Start *****'); 
    $this -> getAchievement();
    $this -> logger -> notice('***** $this -> getAchievement() End *****'); 

    $this -> logger -> notice('***** $this -> sendReward() Start *****'); 
    $this -> sendReward();
    $this -> logger -> notice('***** $this -> sendReward() End *****'); 

    $this -> logger -> notice('————————————————' . $this -> currentTime . '————————————————');
    $this -> logger -> commit();
  }

  public function getAchievement() {
    $userAchievements = UserAchievementModel::find([
      'conditions' => 'day_amount_left > 0 AND day_amount_right > 0',
      'order' => 'user_id DESC'
    ]);
    
    if($userAchievements -> valid()) {
      // 发放奖励手续费
      $USER_GOODS_REWARD_SERVICE_CHARGE = $this -> getParameter('USER_GOODS_REWARD_SERVICE_CHARGE');
      $USER_GOODS_REWARD_SERVICE_CHARGE['value'] = $USER_GOODS_REWARD_SERVICE_CHARGE['value'] / 100;

      foreach($userAchievements as $userAchievement) {
        echo '...';
        $amountLeft = $userAchievement -> day_amount_left / 1500;
        $amountRight = $userAchievement -> day_amount_right / 1500;

        if($amountLeft > $amountRight) {
          $amount = $amountRight;
        } else {
          $amount = $amountLeft;
        }
        if($amount > 24) {
          $amount = 24;
        }

        $amount = $amount * 150;
        
        $UserAchievementLogLeftModel = new UserAchievementLogModel([
          'user_id' => $userAchievement -> user_id,
          'from_user_id' => $userAchievement -> user_id,
          'type' => 711,
          'create_time' => $this -> currentTime,
          'amount' => $userAchievement -> day_amount_left
        ]);
        if(!$UserAchievementLogLeftModel -> create()) {
          $messages = $UserAchievementLogLeftModel -> getMessages();
          $this -> logger -> error('LINE: ' . __LINE__ . ', $UserAchievementLogLeftModel->create():' .  $messages[0] -> getMessage());
        }
        $UserAchievementLogRightModel = new UserAchievementLogModel([
          'user_id' => $userAchievement -> user_id,
          'from_user_id' => $userAchievement -> user_id,
          'type' => 712,
          'create_time' => $this -> currentTime,
          'amount' => $userAchievement -> day_amount_right
        ]);
        if(!$UserAchievementLogRightModel -> create()) {
          $messages = $UserAchievementLogRightModel -> getMessages();
          $this -> logger -> error('LINE: ' . __LINE__ . ', $UserAchievementLogRightModel->create():' .  $messages[0] -> getMessage());
        }

        $UserWalletGoodsLogModel = new UserWalletGoodsLogModel([
          'user_id' => $userAchievement -> user_id,
          'from_user_id' => $userAchievement -> user_id,
          'type' => 83,
          'active' => 1,
          'is_draw' => 0,
          'draw_time' => 0,
          'create_time' => $this -> currentTime,
          'amount' => $amount,
          'amount_new' => 0,
          'amount_old' => 0,
          'service_charge' => $amount * $USER_GOODS_REWARD_SERVICE_CHARGE['value'],
          'remark' => '计划任务 - 对碰奖'
        ]);
        if(!$UserWalletGoodsLogModel -> create()) {
          $messages = $UserWalletGoodsLogModel -> getMessages();
          $this -> logger -> error('LINE: ' . __LINE__ . ', $UserWalletGoodsLogModel->create():' .  $messages[0] -> getMessage());
        }

        $userAchievement -> day_amount_left = 0;
        $userAchievement -> day_amount_right = 0;
        if(!$userAchievement -> save()) {
          $messages = $userAchievement -> getMessages();
          $this -> logger -> error('LINE: ' . __LINE__ . ', $userAchievement->create():' .  $messages[0] -> getMessage());
        }
      }
    }
  }

  public function sendReward() {
    $userWalletGoodsLogs = UserWalletGoodsLogModel::find([
      'conditions' => 'is_draw = 0',
      'order' => 'id ASC'
    ]);

    if($userWalletGoodsLogs -> valid()) {
      foreach($userWalletGoodsLogs as $userWalletGoodsLog) {
        echo '...';

        $this -> getUserWallets($userWalletGoodsLog -> user_id);

        if(!$this -> __userWallets[$userWalletGoodsLog -> user_id]) {
          $this -> logger -> warning('LINE: ' . __LINE__ . ', user_id: ' .  $userWalletGoodsLog -> user_id . ',此用户不存在.');
        } else {
          $userWalletGoodsLog -> amount_old = $this -> __userWallets[$userWalletGoodsLog -> user_id] -> goods;
          $userWalletGoodsLog -> is_draw = 1;
          switch($userWalletGoodsLog -> active) {
            case '0':
                $this -> __userWallets[$userWalletGoodsLog -> user_id] -> goods -= $userWalletGoodsLog -> amount;
              break;
            case '1':
                $this -> __userWallets[$userWalletGoodsLog -> user_id] -> goods += ($userWalletGoodsLog -> amount - $userWalletGoodsLog -> service_charge);
              break;
            default:
              $this -> logger -> warning('LINE: ' . __LINE__ . ', active: ' .  $userWalletGoodsLog -> active . ',日志有误');
              break;
          }

          $userWalletGoodsLog -> amount_new = $this -> __userWallets[$userWalletGoodsLog -> user_id] -> goods;
          $userWalletGoodsLog -> draw_time = strtotime('+1 day ' . date('Y-m-d 00:00:00', $userWalletGoodsLog -> create_time));
          if(!$userWalletGoodsLog -> save()) {
            $this -> logger -> error('LINE: ' . __LINE__ . ', $userWalletGoodsLog -> save(), id:' . $userWalletGoodsLog -> id . '.');
          }
        }
      }

      if(!empty($this -> __userWallets)) {
        foreach($this -> __userWallets as $userWallet) {
          if(!$userWallet -> save()) {
            $this -> logger -> error('LINE: ' . __LINE__ . ', $userWallet -> save(), id:' . $userWallet -> user_id . '.');
          }
        }
      }
    }
  }

  private $__userWallets=[];
  public function getUserWallets($user_id = null){
    if(is_null($user_id)) {
      return $this -> __userWallets;
    }

    if(isset($this -> __userWallets[$user_id])) {
      return $this -> __userWallets[$user_id];
    }

    return $this -> __userWallets[$user_id] = UserWalletModel::findFirst('user_id = ' . $user_id);
  }
}